package com.example.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class MapTask implements Runnable{
    private static final String TAG = "MapTask";
    private Handler handler;

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        Log.i(TAG,"run:Running......");
        try {
            Thread.sleep(2000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }


        Bundle bundle = new Bundle();
        ArrayList<HashMap<String, String>> reList =new ArrayList<>();
        try {
            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj").get();
            String title = doc.title();
            Log.i(TAG,"run:title="+title);


            Elements tables = doc.getElementsByTag("table");
            Element table2 = tables.get(1);
            Elements trs = doc.getElementsByTag("tr");
            for(Element tr:trs){
                Elements tds = tr.getElementsByTag("td");
                for(int i=1;i<tds.size();i+=8){
                    String td1 = tds.get(i-1).text();
                    String td2 = tds.get(i+4).text();

            //        String str1 = td1.text();
              //      String val = td2.text();

                    Log.i(TAG,"run:"+td1+"==>"+td2);
           //         reList.add(str1+"==>"+val);

                    HashMap<String, String> map = new HashMap<String,String>();
                    map.put("cname",td1);
                    map.put("cval",td2);
                    reList.add(map);

                }
            }
            //body > section > div > div > article > table > tbody > tr:nth-child(2) > td.bz > a
            //body > section > div > div > article > table > tbody > tr:nth-child(2) > td:nth-child(6)
            //body > div > div.BOC_main > div.publish > div:nth-child(3) > table > tbody > tr:nth-child(2) > td:nth-child(1)
            //body > div > div.BOC_main > div.publish > div:nth-child(3) > table > tbody > tr:nth-child(2) > td:nth-child(4)

        } catch (IOException e) {
            e.printStackTrace();
        }

        Message msg = handler.obtainMessage(5,reList);
        handler.sendMessage(msg);
        Log.i(TAG,"run:sendMessage ok");


    }

    }

